using MediatR;
using Order.Api.Write.Application.Command;
using Order.Api.Write.Service;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Order.Api.Write.Application.Handler
{
    /// <summary>
    /// 退款状态更新处理器
    /// </summary>
    public class RefundStatusUpdateHandler : IRequestHandler<RefundStatusUpdateCommand, bool>
    {
        private readonly IRefundService _refundService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="refundService">退款服务</param>
        public RefundStatusUpdateHandler(IRefundService refundService)
        {
            _refundService = refundService ?? throw new ArgumentNullException(nameof(refundService), "退款服务不能为空");
        }

        /// <summary>
        /// 处理退款状态更新请求
        /// </summary>
        /// <param name="request">退款状态更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<bool> Handle(RefundStatusUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 参数验证
                if (request == null)
                {
                    throw new ArgumentNullException(nameof(request), "状态更新请求不能为空");
                }

                // 构建状态更新命令
                var command = new Order.Api.Write.Dto.Refund.RefundStatusUpdateCommand
                {
                    RefundId = request.RefundId,
                    TargetStatus = request.TargetStatus,
                    Remark = request.Remark
                };

                // 调用服务层方法进行状态更新
                var result = await _refundService.UpdateRefundStatusAsync(command);
                return result;
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // TODO: 添加日志记录
                throw new Exception($"处理退款状态更新请求时发生错误: {ex.Message}", ex);
            }
        }
    }
}